package com.guiji.quartz.domain;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.wanghaomiao.xpath.model.JXDocument;
import com.guiji.quartz.config.ProxyConfig;
import com.guiji.quartz.task.DataSaveUtil;
import com.guiji.quartz.util.DelPicUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: cms-vue-plus
 * @description:
 * @author: wangxw
 * @date 2022/1/11 16:31
 */
public class ZimbioMovies {
	private static final Logger log = LoggerFactory.getLogger(ZimbioMovies.class);
	private static final String host = "https://www.zimbio.com";
	private static final String baseUrl = "https://www.zimbio.com/specials/Movies";
	private static final boolean needProxy = false;

	static {
		System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
	}

	public static void mainMethod() throws Exception {

		HttpResponse response = null;
		try {
			HttpRequest request = HttpRequest.get(baseUrl)
				.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
				.header("Accept-Encoding", "gzip, deflate")
				.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36");
			if (needProxy) {
				request = request.setHttpProxy(ProxyConfig.url, ProxyConfig.ip);
			}
			response = request.setConnectionTimeout(30000).execute();

			if (null != response && response.getStatus() == 200) {
				List<HttpCookie> cookies = response.getCookies();
				String resp = response.body();
				Set<String> resUrl = getUrl(resp);
				getContent(resUrl, cookies);
			} else {
				log.error(baseUrl + String.valueOf(response.getStatus()));
			}

		} catch (Exception e) {
			log.error(String.format("访问 %s 失败", baseUrl));
			return;
		}
	}


	private static void getContent(Set<String> listContent, List<HttpCookie> cookies) throws MalformedURLException, URISyntaxException, InterruptedException {
		for (String url : listContent) {

			Thread.sleep(1000);
			if (!url.startsWith("https")) {
				url = new StringBuffer(host).append(url).toString();
			}
			if (null != cookies && cookies.size() > 0) {
				CookieManager ccm = new CookieManager();
				CookieStore CookieStore = ccm.getCookieStore();
				for (HttpCookie cookie : cookies) {
					URL domain = new URL(host);
					CookieStore.add(domain.toURI(), cookie);
				}
				HttpRequest.setCookieManager(ccm);
			}

			log.info("getContent执行到-{},listContent长度-{}", url, listContent.size());
			String doc;
			JXDocument jxDocument;
			try {
				HttpResponse response = null;
				HttpRequest request = HttpRequest.get(url)
					.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36")
					.header("Refer", baseUrl);
				if (needProxy) {
					request = request.setHttpProxy(ProxyConfig.url, ProxyConfig.ip);
				}

				response = request.setConnectionTimeout(30000).execute();
				doc = response.body();


				String pattern1 = "var slideshowId = '(.*?)',";
				String pattern2 = "slideId = '(.*?)',";
				Pattern p1 = Pattern.compile(pattern1);
				Pattern p2 = Pattern.compile(pattern2);
				Matcher m1 = p1.matcher(doc);
				Matcher m2 = p2.matcher(doc);
				if (m1.find() && m2.find()) {
					String slideshowId = m1.group(1);
					String slideId = m2.group(1);
					String ajaxUrl = String.format("https://www.zimbio.com/api/v1/specialsV2?filters[]=%s&count=16&slide_id=%s&offset=-6&platform=desktop", slideshowId, slideId);
					HttpResponse response1 = null;
					HttpRequest request1 = HttpRequest.get(ajaxUrl)
						.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36")
						.header("Refer", url);
					if (needProxy) {
						request1 = request1.setHttpProxy(ProxyConfig.url, ProxyConfig.ip);
					}
					response1 = request1.setConnectionTimeout(30000).execute();
					doc = response1.body();


					JSONObject jobj = JSONUtil.parseObj(doc);
					JSONArray slides = (JSONArray) jobj.get("slides");
					String title = (String) jobj.get("title");
					StringBuffer contents =new StringBuffer();
					List<Object> srcImgs = new ArrayList<>();
					StringBuffer description =new StringBuffer();
					if (slides != null && slides.size() > 0) {
//						JSONObject slide = (JSONObject) slides.get(0);
						for(int k=0;k<slides.size();k++) {
							JSONObject slide = (JSONObject) slides.get(k);
							String content = (String) slide.get("desc");
							content = content.replace("<em>", "");
							content = content.replace("</em>", "");
							content = content.replace("&nbsp;", " ");
							content = content.replace("<br />", "$$$");
							content = content.replace("(Editor's note: This list applies to Netflix in the United States only.)", "");

							String pattern = "<strong>(.*?)</strong>";
							Pattern p = Pattern.compile(pattern);
							Matcher m = p.matcher(content);
							while (m.find()) {
								String repStr = m.group();
								content = content.replace(repStr,"");
							}

							contents.append("$$$");
							contents.append(content);
							JSONObject meta = (JSONObject) slide.get("meta");
							String img = (String) meta.get("image");
							String slideTitle = (String) slide.get("title");
							if(slideTitle!=null&&slideTitle.length()>1) {
								description.append("#");
								description.append(slideTitle);
							}

							srcImgs.add(img);


						}
						String resultContent =contents.toString();
						resultContent= resultContent.replace("\n","");
//						List<String> newImgs = null;
						List<String> newImgs = DelPicUtil.delPic(srcImgs);

						Date date = new Date();
						if (resultContent.length() > 50000 || resultContent.replaceAll("\\$|[\\s\\p{Zs}]", "").length() < 20 || srcImgs.size() > 20) {
							continue;
						}
						try {
							System.out.println("=======================================================");
							System.out.println(url);
							System.out.println(title);

							for (Object imgitem : srcImgs) {
								System.out.println(" " + imgitem);
							}

							System.out.println(resultContent);

							System.out.println(description);
							System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
							DataSaveUtil.saveData1(title, resultContent, newImgs, url, date, baseUrl, "zimbio-Movies", description.toString());
							log.info(Thread.currentThread().getName() + "-----------------zimbio-Movies----------------");
						} catch (Exception e) {
							continue;
						}
					}

				}

			} catch (Exception e) {
				log.info("代理失败2" + e);
				continue;
			}


		}
	}

	private static Set<String> getUrl(String content) {
		Set<String> res = new HashSet<>();


		JXDocument jxDocument = new JXDocument(content);
		int imgSize = 0;
		try {
			imgSize = jxDocument.sel("//div[@id='Content']//a/@href").size();
			if (imgSize > 0) {

				for (int k = 0; k < imgSize; k++) {
					String temp = null;
					temp = jxDocument.sel("//div[@id='Content']//a/@href").get(k).toString();
					temp = temp.strip();
					if (temp.contains("+")) {
						res.add(temp);

					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return res;
	}

//
//	public static void main(String[] args) throws Exception {
//		mainMethod();
//	}

}





